/**
 * 后台定时任务服务入口，独立于与前端交互接口http服务。用于后台日程提醒定时动作和提醒时间正确性的自动维护
 */

require('../conf/dbInit').init();
var CronJob = require('cron').CronJob;
var moment = require('moment');
var msgRemind = require('./msgRemind');
var correctionRemindTime = require('./correctionRemindTime');
var logs = require('../conf/logs');

var scheduledServer = function(){
    var msgRemindJob = new CronJob({
        cronTime: '0 */1 * * * *',
        onTick: function() {
            console.info("%s:定时消息发送轮训扫描开始", moment().format('YYYY-MM-DD HH:mm:ss'));

            // 如果上一次任务已经完成，则进行此次任务
            if (global.isLastComplete != false) {
                global.isLastComplete = false;

                try {
                    msgRemind.start();
                } catch (err) {
                    console.error('定时消息轮训任务发生异常：%s', JSON.stringify(err));
                    global.isLastComplete = true;
                }
            }
        },
        start: false
    });

    var correctionTimeJob = new CronJob({
        cronTime: '0 0 1 * * *',
        onTick: function() {
            console.info("%s:定时纠正异常提醒时间任务开始", moment().format('YYYY-MM-DD HH:mm:ss'));

            try {
                correctionRemindTime.start();
            } catch (e) {
                console.error('定时纠正异常提醒时间任务发生异常：%s', JSON.stringify(e));
            }
        },
        start: false
    });

    var start = function(){
        msgRemindJob.start();
        correctionTimeJob.start();
    };

    var init = function() {
        global.client_id = '3799249803934DE99495C9584AE68449';
        global.client_secret = 'F07B8035741F42D7A0D7F6F71F98CB1A';
        logs.init();
        return this;
    };

    return {
        init  : init,
        start : start
    };
}();

scheduledServer.init().start();

